package com.tuanzi.loan.business.repository.banana.collaborate.impl;

import com.tuanzi.loan.business.repository.banana.collaborate.custom.RegistryRepositoryCustom;
import com.tuanzi.loan.core.repository.JOOQBaseRepository;
import com.tuanzi.loan.vo.request.Collaborate.CollaborateStatListRequest;
import com.tuanzi.loan.vo.response.collaborate.CollaborateStatListResponse;
import com.tuanzi.server.loan_base.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.jooq.Record9;
import org.jooq.SelectConditionStep;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

import static com.tuanzi.loan.generated.jooq.banana_stat.tables.StatBananaActivityRegister.STAT_BANANA_ACTIVITY_REGISTER;
import static com.tuanzi.loan.generated.jooq.banana_stat.tables.StatBananaCollaborateRegister.STAT_BANANA_COLLABORATE_REGISTER;
import static com.tuanzi.loan.generated.jooq.stat.Tables.STAT_COLLABORATE_REGISTER;

/**
 * 描述:
 *
 * @author YJM
 * @create 2018-11-15 4:51 PM
 */
@Repository
public class RegistryRepositoryImpl extends JOOQBaseRepository implements RegistryRepositoryCustom {

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	@Override
	protected TableImpl getTable() {
		return STAT_COLLABORATE_REGISTER;
	}

	@Override
	public Page<CollaborateStatListResponse> list(CollaborateStatListRequest searchRequest, Pageable pageable) {
		//当前时间
		List<Integer> channelList = searchRequest.getChannelList();

		StringBuilder sql = new StringBuilder();
        SelectConditionStep<Record9<Date, String, String, Integer, String, Integer, Integer, Integer, Integer>> collaborate = dslContext.select(STAT_BANANA_COLLABORATE_REGISTER.CDATE, STAT_BANANA_COLLABORATE_REGISTER.PRD_ID, STAT_BANANA_COLLABORATE_REGISTER.PLATFORM
                , STAT_BANANA_COLLABORATE_REGISTER.CHANNEL, STAT_BANANA_COLLABORATE_REGISTER.ACTIVITY_ID, STAT_BANANA_COLLABORATE_REGISTER.EXTERNAL_REGISTER_COUNT
                , STAT_BANANA_COLLABORATE_REGISTER.EXTERNAL_NEW_REGISTER_COUNT, STAT_BANANA_COLLABORATE_REGISTER.APP_ACTIVATE_COUNT
                , STAT_BANANA_COLLABORATE_REGISTER.APP_ACTIVATE_COUNT_PHONE).from(STAT_BANANA_COLLABORATE_REGISTER).where(STAT_BANANA_COLLABORATE_REGISTER.CHANNEL
                .in(channelList));
        SelectConditionStep<Record9<Date, String, String, Integer, String, Integer, Integer, Integer, Integer>> commRegister = dslContext.select(STAT_BANANA_ACTIVITY_REGISTER.CREATE_DATE, STAT_BANANA_ACTIVITY_REGISTER.PRODUCT_ID, STAT_BANANA_ACTIVITY_REGISTER.PLATFORM
                , STAT_BANANA_ACTIVITY_REGISTER.CHANNEL, STAT_BANANA_ACTIVITY_REGISTER.ACTIVITY_ID, STAT_BANANA_ACTIVITY_REGISTER.H5_RECORD, STAT_BANANA_ACTIVITY_REGISTER.H5_REGISTER
                , STAT_BANANA_ACTIVITY_REGISTER.APP_LOGIN, STAT_BANANA_ACTIVITY_REGISTER.APP_REGISTER).from(STAT_BANANA_ACTIVITY_REGISTER).where(
                STAT_BANANA_ACTIVITY_REGISTER.CREATE_DATE.eq(new Date(new java.util.Date().getTime())).and(STAT_BANANA_ACTIVITY_REGISTER.CHANNEL.in(channelList))
        );

		sql.append("  1=1 ");
		//添加查询条件
		java.util.Date startDate = searchRequest.getStartDate();
		if(null != startDate){
			sql.append(" and a.cdate >=").append("'").append(DateUtils.formatDateToYyyyMMdd(startDate)).append("'");
		}

		java.util.Date endDate = searchRequest.getEndDate();
		if(null != endDate){
			sql.append(" and a.cdate <=").append("'").append(DateUtils.formatDateToYyyyMMdd(endDate)).append("'");
		}

		String platform = searchRequest.getPlatform();
		if(org.apache.commons.lang3.StringUtils.isNotBlank(platform)){
			sql.append(" and a.platform='").append(platform).append("'");
		}

		String activityId = searchRequest.getActivityId();
		if(org.apache.commons.lang3.StringUtils.isNotBlank(activityId)){
			sql.append(" and a.activity_id='").append(activityId).append("'");
		}

		String channelId = searchRequest.getChannelId();
		if(org.apache.commons.lang3.StringUtils.isNotBlank(channelId)){
			sql.append(" and a.channel='").append(channelId).append("'");
		}

		String productId = searchRequest.getProductId();
		if(org.apache.commons.lang3.StringUtils.isNotBlank(productId)){
			sql.append(" and a.prd_id='").append(productId).append("'");
		}
        String sql1 = dslContext.select().from(commRegister.unionAll(collaborate)).where(sql.toString()).orderBy(STAT_BANANA_ACTIVITY_REGISTER.CREATE_DATE.as("create_date").desc())
                .getSQL();

		String querySql = sql1 + " LIMIT ?,?";

		//查询数量sql
		String countSql = "SELECT COUNT(*) AS num FROM (" + querySql + ")d";

		Object[] params= {DateUtils.getCurrentDate(),StringUtils.join(channelList, ","),StringUtils.join(channelList, ","),pageable.getOffset(), pageable.getPageSize()};

		Long count = dslContext.fetchOne(countSql, params).into(Long.class);

        List<CollaborateStatListResponse> list = dslContext.fetch(querySql, params).map(record -> {
			CollaborateStatListResponse response = new CollaborateStatListResponse();
			response.setDate(record.get(STAT_BANANA_ACTIVITY_REGISTER.CREATE_DATE));
			response.setProductId(record.get(STAT_BANANA_ACTIVITY_REGISTER.PRODUCT_ID));
			response.setChannelId(record.get(STAT_BANANA_ACTIVITY_REGISTER.CHANNEL,String.class));
			response.setPlatform(record.get(STAT_BANANA_ACTIVITY_REGISTER.PLATFORM));
			response.setActivityId(record.get(STAT_BANANA_ACTIVITY_REGISTER.ACTIVITY_ID));
			response.setExternalRegisterCount(record.get(STAT_BANANA_ACTIVITY_REGISTER.H5_RECORD));
			response.setExternalNewRegisterCount(record.get(STAT_BANANA_ACTIVITY_REGISTER.H5_REGISTER));
			response.setAppActivateCount(record.get(STAT_BANANA_ACTIVITY_REGISTER.APP_LOGIN));
			response.setAppActivateCountPhone(record.get(STAT_BANANA_ACTIVITY_REGISTER.APP_REGISTER));
			return response;
		});

		return new PageImpl<>(list, pageable, count);
	}

}
